package main

import (
	"StudentManagment/dataBase"
	"encoding/json"
	"github.com/google/uuid"
	"log"
	"net/http"
	"strconv"
)

/*
空return：当遇到错误时，函数会立即返回，停止后续操作，不再执行后续代码
*/

// 处理跨越请求
func enableCORS(nextHttp http.HandlerFunc) http.HandlerFunc {
	return func(rw http.ResponseWriter, request *http.Request) {
		// 设置所有域可以访问
		rw.Header().Set("Access-Control-Allow-Origin", "*")
		// 设置允许的请求头
		rw.Header().Set("Access-Control-Allow-Headers", "Content-Type")
		// 设置允许的方法
		rw.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")

		// 处理预检请求(OPTIONS)
		if request.Method == http.MethodOptions {
			rw.WriteHeader(200)
			return
		}

		// 继续处理实际请求
		nextHttp.ServeHTTP(rw, request)
	}
}

func main() {
	// 初始化数据库
	dataBase.Init()
	// 注册路由和处理函数(应用CORS中间件)
	http.HandleFunc("/insert", enableCORS(insertCreate))         // 插入数据
	http.HandleFunc("/get-all-data", enableCORS(handlerGetData)) // 获取数据
	http.HandleFunc("/update", enableCORS(handlerUpdate))        // 更新数据
	http.HandleFunc("/delete", enableCORS(handlerDelete))        // 删除数据

	// 启动服务器
	log.Println("Server Starting ok...")
	log.Fatal(http.ListenAndServe(":8000", nil))

}

var params map[string]string

// 创建数据
func insertCreate(w http.ResponseWriter, r *http.Request) {
	// 1.解析请求体中的JSON数据
	if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
		log.Printf("JSON解析错误:%v", err)
		http.Error(w, "无效的数据请求", 400)
		return
	}

	// 初始化学生对象
	student := dataBase.StudentInfo{}

	// 4. 生成唯一ID
	id := uuid.New().String()
	student.ID = id

	// 解析并验证姓名
	name, nameOk := params["name"]
	if !nameOk || name == "" {
		http.Error(w, "stuName not is nil：", http.StatusBadRequest)
		return
	}
	student.Name = name

	// 解析并验证性别
	sex, sexOk := params["sex"]
	if !sexOk || (sex != "男" && sex != "女") {
		http.Error(w, "Invalid sex", http.StatusBadRequest)
		return
	}
	student.Sex = sex

	// 解析并验证年龄
	age, ageOk := params["age"]
	if !ageOk {
		http.Error(w, "Age is required", http.StatusBadRequest)
		return
	}
	_, err := strconv.Atoi(age)
	if err != nil {
		http.Error(w, "Invalid age format", http.StatusBadRequest)
		return
	}
	student.Age = age

	// 解析班级
	class, classOk := params["class"]
	if classOk && len(class) > 0 {
		student.Class = class
	}

	// 解析班主任
	teacher, teacherOk := params["teacher"]
	if teacherOk && len(teacher) > 0 {
		student.MasterTeacher = teacher
	}

	// 解析电话号码
	phone, phoneOk := params["phone"]
	if phoneOk && len(phone) > 0 {
		student.PhoneNumber = phone
	}

	// 解析地址
	address, addressOk := params["adders"]
	if addressOk && len(address) > 0 {
		student.Adders = address
	}

	// 设置默认在校状态

	inschool, inschoolOK := params["inSchool"]
	if inschoolOK && inschool == "true" {
		student.InSchool = true
	} else {
		// 设置默认在校状态
		student.InSchool = false
	}

	// 保存到数据库
	if err := dataBase.CreateStuData(student); err != nil {
		log.Printf("数据库保存错误: %v", err)
		http.Error(w, "服务器内部错误", http.StatusInternalServerError)
		return
	}

	w.WriteHeader(200)
	w.Write([]byte("学生添加成功"))
	clear(params)
}

// 获取数据
func handlerGetData(w http.ResponseWriter, r *http.Request) {
	stuList, err := dataBase.GetAllStuInfo()
	if err != nil {
		log.Printf("获取待办项错误: %v", err)
		http.Error(w, "服务器内部错误", http.StatusInternalServerError)
		return
	}
	// 2. 如果没有任何待办项，返回空数组
	if len(stuList) == 0 {
		stuList = []dataBase.StudentInfo{} // 确保返回空数组而不是null
	}
	// 3. 设置JSON响应头
	w.Header().Set("Content-Type", "application/json")
	// 4. 将数据以json格式发送
	if err := json.NewEncoder(w).Encode(stuList); err != nil {
		log.Printf("JSON编码错误: %v", err)
		http.Error(w, "服务器内部错误", http.StatusInternalServerError)
	}
	clear(params)
}

// 删除数据
func handlerDelete(w http.ResponseWriter, r *http.Request) {
	// 1.解析请求体 -- 其功能是把 HTTP 请求体里的 JSON 数据解析成 Go 结构体或者其他数据类型
	if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
		log.Printf("JSON解析错误：%v", err)
		http.Error(w, "无效的请求数据", http.StatusBadRequest)
		return
	}

	// 获取用户ID
	id, idOk := params["id"]
	if !idOk || id == "" {
		http.Error(w, "学生ID不能为空", http.StatusBadRequest)
		return
	}
	// 从数据库中删除数据
	if err := dataBase.DeleteStuInfo(id); err != nil {
		log.Printf("删除错误：%v", err)
		http.Error(w, "服务器内部错误", http.StatusBadRequest)
		return
	}
	// 返回成功响应
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte("ID为" + id + "的学生删除成功！"))
}

// 更新数据
func handlerUpdate(w http.ResponseWriter, r *http.Request) {
	if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
		log.Printf("JSON解析错误：%v", err)
		http.Error(w, "无效的请求数据", http.StatusBadRequest)
		return
	}
	// 初始化学生对象
	student := dataBase.StudentInfo{}

	// 修改id
	id, _ := params["id"]
	if id == "" {
		http.Error(w, "ID not is nil", http.StatusBadRequest)
		return
	}
	student.ID = id

	// 解析并验证姓名
	name, nameOk := params["name"]
	if !nameOk || name == "" {
		http.Error(w, "stuName not is nil：", http.StatusBadRequest)
		return
	}
	student.Name = name

	// 解析并验证性别
	sex, sexOk := params["sex"]
	if !sexOk || (sex != "男" && sex != "女") {
		http.Error(w, "Invalid sex", http.StatusBadRequest)
		return
	}
	student.Sex = sex

	// 解析并验证年龄
	age, ageOk := params["age"]
	if !ageOk {
		http.Error(w, "Age is required", http.StatusBadRequest)
		return
	}
	_, err := strconv.Atoi(age)
	if err != nil {
		http.Error(w, "Invalid age format", http.StatusBadRequest)
		return
	}
	student.Age = age

	// 解析班级
	class, classOk := params["class"]
	if classOk && len(class) > 0 {
		student.Class = class
	}

	// 解析班主任
	teacher, teacherOk := params["teacher"]
	if teacherOk && len(teacher) > 0 {
		student.MasterTeacher = teacher
	}

	// 解析电话号码
	phone, phoneOk := params["phone"]
	if phoneOk && len(phone) > 0 {
		student.PhoneNumber = phone
	}

	// 解析地址
	address, addressOk := params["adders"]
	if addressOk && len(address) > 0 {
		student.Adders = address
	}

	// 修改默认在校状态
	inschool, inschoolOK := params["inSchool"]
	if inschoolOK && inschool == "true" {
		student.InSchool = true
	}

	// 6. 更新数据库
	if err := dataBase.UpdateStuInfo(student); err != nil {
		log.Printf("更新错误: %v", err)
		http.Error(w, "服务器内部错误", http.StatusInternalServerError)
		return
	}

	// 7. 返回成功响应
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte("任务更新成功"))
	clear(params)
}
